package com.zjj.lbw.spring6.controller;

import com.zjj.lbw.spring6.entity.Order;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ZjjController {
    @GetMapping("/public")
    public String publicPage() {
        return "Public Access";
    }

    @GetMapping("/private")
    public String privatePage() {
        return "Authenticated Access";
    }

    @GetMapping("/index")
    public String index() {
        return "index access";
    }

    @GetMapping("/fail")
    public String fail() {
        return "fail access";
    }

    @GetMapping("/private2")
    public String private2Page() {
        return "Authenticated2 Access";
    }

    @PostMapping("/post")
    public String post() {
        return "Post Access";
    }

    @GetMapping("/read")
    public String read() {
        return "read success";
    }

    @GetMapping("/delete")
    public String delete() {
        return "delete success";
    }

    @GetMapping("/write")
    public String write() {
        return "write success";
    }

    @PreFilter("filterObject.user == authentication.name")
    @PostMapping("/preFilter")
    public void deleteOrders(@RequestBody List<Order> orders) {
        System.out.println(orders.get(0).getUser());
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/preAuthorize")
    public String deleteUser() {
        return "delete success";
    }

    @PostAuthorize("returnObject.user == authentication.name")
    @GetMapping("/postAuthorize")
    public Order getOrder() {
        Order order = new Order();
        order.setId(1);
        order.setUser("13888888888");
        return order;
    }

    @PostFilter("filterObject.user == authentication.name or hasRole('ADMIN')")
    @GetMapping("/postFilter")
    public List<Order> getAllOrders() {
        Order order1 = new Order();
        order1.setId(1);
        order1.setUser("13888888888");

        Order order2 = new Order();
        order2.setId(2);
        order2.setUser("13777777777");

        return List.of(order1, order2);
    }

}
